package com.allwees.bs.task.product;

import com.google.common.collect.Sets;
import com.allwees.bs.core.model.constant.CacheName;
import com.allwees.bs.module.pms.service.PlatformProductService;
import com.allwees.core.cache.RedisUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * 同步禁止加价商品至内存-手动执行
 * @Author Daniel
 * @Version 1.0.0
 * @Description
 * @CreateTime 2020/9/4 16:01
 */
@Slf4j
@Component
public class PriceAdjustForbidSyncTask {
    @Autowired
    private PlatformProductService platformProductService;

    @XxlJob(value="priceAdjustForbidSyncTask")
    public ReturnT<String> execute(String param) {
        log.info(">>>> price adjust forbid sync task begin...");
        Set<String> uuidInDatabase = platformProductService.allForbiddenUuids();
        Set<Object> uuidInCache = RedisUtil.hkeys(CacheName.PROD_FORBID_ADJUST_PRICE);

        if(CollectionUtils.isEmpty(uuidInDatabase)){
            if(CollectionUtils.isEmpty(uuidInCache)){
                return ReturnT.SUCCESS;
            }
            uuidInCache.forEach(hkey ->  RedisUtil.hdel(CacheName.PROD_FORBID_ADJUST_PRICE,hkey));
            return ReturnT.SUCCESS;
        }

        if(CollectionUtils.isEmpty(uuidInCache)){
            uuidInDatabase.forEach(uuid -> RedisUtil.hset(CacheName.PROD_FORBID_ADJUST_PRICE,uuid,1));
        } else {
            Sets.SetView<String> onlyInDatabase = Sets.difference(uuidInDatabase, uuidInCache);
            if(!CollectionUtils.isEmpty(onlyInDatabase)){
                onlyInDatabase.forEach(uuid -> RedisUtil.hset(CacheName.PROD_FORBID_ADJUST_PRICE,uuid,1));
            }
            Sets.SetView<Object> onlyInCache = Sets.difference(uuidInCache, uuidInDatabase);
            if(!CollectionUtils.isEmpty(onlyInCache)){
                onlyInCache.forEach(uuid -> RedisUtil.hdel(CacheName.PROD_FORBID_ADJUST_PRICE,uuid));
            }
        }
        log.info("<<<< price adjust forbid sync task end...");
        return ReturnT.SUCCESS;
    }
}
